package dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import dao.CategoryDAO;
import entity.Category;

public class HibernateCategoryDAO extends HibernateDaoSupport implements CategoryDAO{

	@Override
	public List<Category> findAll() throws Exception {
		String hql="from Category";
		return getHibernateTemplate().find(hql);
	}

	@Override
	public Category findById(int id) throws Exception {
		return (Category) getHibernateTemplate().get(Category.class, id);
	}

	@Override
	public List<Category> findByParentId(int parendId) throws Exception {
		String hql="select distinct c from Category c left join fetch c.catelist where c.parentId=?";
		Object[] params = {parendId};
		List<Category> list = getHibernateTemplate().find(hql,params);
		return list;
	}

	@Override
	public Map<Integer,String> findBYProId(int id) throws Exception {
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Map<Integer,String> map = new HashMap<Integer,String>();
		String sql="select dcp.cat_id,c.name from d_category_product dcp join d_category c on  dcp.cat_id=c.id  where product_id=? order by dcp.cat_id asc";
		SQLQuery query = session.createSQLQuery(sql);
		query.setInteger(0, id);
		List<Object[]> list = query.list();
		for(Object[] objs:list){
			map.put((Integer)objs[0], objs[1].toString());
		}
		session.close();
		return map;
	}
	
}
